import java.util.*;
class Graph
{
	int g[][],v,e;
void createGraph()
{
	 Scanner t = new Scanner(System.in);
	 int a,b,w;
	 System.out.println("Enter the number of vertices:");
	 v = t.nextInt();
	 System.out.println("Enter the number of Edges:");
	 e = t.nextInt();
	 
	 g = new int[v+1][v+1];
	 
	 for(int i=1;i<=v;i++)
	 for(int j=1;j<=v;j++)
	 g[i][j] =0;
	 
	 for(int i=1;i<=e;i++)
	 {
	 	System.out.println("Enter the Edge Information: ");
	 	    a = t.nextInt();
	 	    b = t.nextInt();
	 	    
	    System.out.println("Enter weight of the edge: ");
	 	    w = t.nextInt();
	 	    g[a][b] = g[b][a] = w;
	 }
}
void prim()
{
	int d[], p[], visited[];
			int current;
			
			d = new int[v+1];
			p = new int[v+1];
			visited = new int[v+1];
			for(int i=1;i<=v;i++)
			{
				d[i] = 32767;
				p[i] = visited[i] = 0;
			}
			current = 1;
			d[current] = 0;
			visited[current] = 1;
			int c = 1;
			while(c!=v)
			{
				
				for(int i=1;i<=v;i++)
				{
					if(g[current][i]!=0 && visited[i]!=1)
					if(g[current][i] <d[i])
					{
						d[i] = g[current][i];
						p[i] = current;
					}
				}
				int min = 32767;
				for(int i=1;i<=v;i++)
				{
					if(visited[i]!=1)
						if(d[i] < min) 
						{
							min = d[i];
							current = i;
						}
							
			}
				visited[current] = 1;
				c = c+1;	
			}
			
			int mincost = 0;
			for(int i=1;i<=v;i++)
			mincost = mincost + d[i];
			System.out.println("\n Mincost = "+mincost);
 }
 }
 public class prims
 {
  		public static void main (String[] args)
  	    {
  	    	Graph g = new Graph();
  	    	
  	    	g.createGraph();
  	    	g.prim();
        }
  
 }
